<template>
  <el-upload class="md-upload-card" :style="{width: width, height: height}" :action="action" :headers="headers" :accept="accept" :show-file-list="false" :on-success="onUploadSuccess" :before-upload="onBeforeUpload">
    <img v-if="src" :src="src" class="avatar">
    <div class="tip" v-else>
      <i class="el-icon-plus avatar-uploader-icon"></i>
      <p>{{label}}</p>
    </div>

  </el-upload>
</template>

<script>
export default {
  name: 'MdUploadCardBaseComponent',
  props: {
    value: [String],
    action: {
      type: String,
      default: '/api/file/uploadFile'
    },
    accept: { // 显示上传格式
      type: String,
      default: '.png, .jpg, .jpeg'
    },
    width: {
      type: String,
      default: '150px'
    },
    height: {
      type: String,
      default: '150px'
    },
    limitSize: { // 文件大小
      type: [Number, String],
      default: 50
    },
    label: {
      type: String,
      default: '点击上传LOGO'
    }
  },
  data () {
    return {
      src: null,
      headers: {}
    }
  },
  watch: {
    value: {
      handler (val) {
        this.src = val
      },
      deep: true,
      immediate: true
    }
  },
  mounted () {
    this.headers['Authorization'] = `Bearer ${this.$local.getItem('access_token')}`
    this.src = this.value
  },
  methods: {
    onBeforeUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < this.limitSize
      if (!isLt2M) {
        this.$message.error(`上传文件大小不能超过${50}MB!`)
      }
      return isLt2M
    },
    onUploadSuccess (res) {
      console.log(res)
      if (res.code != 200) {
        this.$message.error(res.msg)
        return
      }
      this.src = res.data.url
      this.$emit('input', res.data.url)
    }
  }
}
</script>

<style lang="scss" scoped>
.md-upload-card {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;

    .tip {
      i {
        font-size: 28px;
        color: #8c939d;
      }

      p {
        font-size: 13px;
        color: #8c939d;
        padding: 0px !important;
        margin: 0px !important;
      }
    }

    img {
      width: auto;
      height: auto;
      max-width: 100%;
      max-height: 100%;
    }
  }
}
</style>